"""
用户认证路由
"""
from datetime import timedelta
from fastapi import APIRouter, HTTPException, status, Response, Depends
from fastapi.responses import JSONResponse

from models.schemas import LoginRequest, LoginResponse, User
from auth.jwt_handler import create_access_token
from auth.dependencies import get_current_user
from utils.response import success_response, error_response
from config import settings


router = APIRouter(prefix="/auth", tags=["用户认证"])


# 模拟用户数据库
MOCK_USERS = {
    "admin": {
        "id": 1,
        "username": "admin",
        "password": "admin123",  # 实际应该是哈希后的密码
        "name": "管理员",
        "role": "admin"
    },
    "operator": {
        "id": 2,
        "username": "operator",
        "password": "operator123",
        "name": "操作员",
        "role": "operator"
    },
    "viewer": {
        "id": 3,
        "username": "viewer",
        "password": "viewer123",
        "name": "访客",
        "role": "viewer"
    }
}


@router.post("/login", summary="用户登录")
async def login(request: LoginRequest, response: Response):
    """
    用户登录认证，返回用户信息和访问令牌
    
    - **username**: 用户名，最少3个字符
    - **password**: 密码，最少6个字符
    
    返回：
    - Token会同时在响应体和Cookie中返回
    - Cookie设置为HttpOnly，前端JavaScript无法访问
    - Max-Age=1800表示30分钟过期
    """
    # 验证用户（模拟）
    user_data = MOCK_USERS.get(request.username)
    
    # 这里直接比较明文密码，实际应该使用bcrypt验证
    if not user_data or user_data["password"] != request.password:
        return JSONResponse(
            status_code=status.HTTP_401_UNAUTHORIZED,
            content=error_response(401, "用户名或密码错误")
        )
    
    # 创建JWT token
    access_token_expires = timedelta(minutes=settings.JWT_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={
            "sub": user_data["username"],
            "user_id": user_data["id"],
            "name": user_data["name"],
            "role": user_data["role"]
        },
        expires_delta=access_token_expires
    )
    
    # 设置HttpOnly Cookie
    response.set_cookie(
        key="token",
        value=access_token,
        httponly=True,
        max_age=settings.JWT_EXPIRE_MINUTES * 60,  # 30分钟
        samesite="strict",
        # secure=True,  # 生产环境启用HTTPS时取消注释
        path="/"
    )
    
    # 返回用户信息和token
    user = User(
        id=user_data["id"],
        username=user_data["username"],
        name=user_data["name"],
        role=user_data["role"]
    )
    
    login_response = LoginResponse(
        user=user,
        token=access_token
    )
    
    return success_response(
        data=login_response.model_dump(),
        message="登录成功"
    )


@router.post("/logout", summary="用户登出")
async def logout(
    response: Response,
    current_user: User = Depends(get_current_user)
):
    """
    用户登出，清除服务端会话和Cookie
    
    需要认证：是
    """
    # 清除Cookie
    response.set_cookie(
        key="token",
        value="",
        httponly=True,
        max_age=0,
        samesite="strict",
        path="/"
    )
    
    return success_response(message="登出成功")
